package flst.ipiweb.struts.action.administrateur;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import flst.ipiweb.proxy.ServiceAdministrateurProxy;
import flst.ipiweb.service.ServiceCrypto;
import flst.ipiweb.transverse.Administrateur;
import flst.ipiweb.transverse.IPIException;

public class NewAdminPostAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		
		//On récupère la session
		HttpSession session = request.getSession();
		if(session.getAttribute("login") == null)
		{
			return mapping.findForward("login");
		}
		
		//Récupération des données du formulaire
		AdminForm vAdminForm = (AdminForm) form;
		Administrateur admin = new Administrateur();
		admin.setNom(vAdminForm.getLastname());
		admin.setPrenom(vAdminForm.getFirstname());
		admin.setLoginUtilisateur(vAdminForm.getLogin());
		//Cryptage du mot de passe
		String password = new ServiceCrypto().encrypt(vAdminForm.getPassword());
		admin.setPassword(password);
		
		//Instanciation du service administrateur
		ServiceAdministrateurProxy sAdministrateur = new ServiceAdministrateurProxy((Boolean) session.getAttribute("isSuper"));
				
		//Création de l'administrateur
		try {
		
			sAdministrateur.createAdministrateur(admin);
			//Message de succes
			session.setAttribute("success", "AdminSuccess.create");
			session.setAttribute("error", null);
		
		} catch (IPIException e) {
			
			//Message d'erreur
			session.setAttribute("error", e.getMessage());
			session.setAttribute("success", null);
			
			return mapping.findForward("new_admin");
		}
		return mapping.findForward("list_admin");
	}

}
